package com.xxlie.core.model;


import com.xxlie.core.common.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;

/**
 * .model
 *
 * @author xxlie.com
 * @since 2017/7/30
 */
public class Page<T> implements Serializable {

    private static final long serialVersionUID = 8041105109091951223L;
    private final int pageNumber;
    private final int pageSize;
    private int totalPages;
    private long totalElements;
    private List<T> content;

    public Page(org.springframework.data.domain.Page<T> page) {

        if (page.getNumber() >= 1) {
            this.pageNumber = page.getNumber() - 1;
        } else {
            this.pageNumber = 0;
        }
        this.pageSize = page.getSize();
        this.totalPages = page.getTotalPages();
        this.totalElements = page.getTotalElements();
        this.content = page.getContent();

    }

    public Page(int pageNumber, int pageSize) {

//        this.pageNumber = pageNumber;
        if (pageNumber >= 1) {
            this.pageNumber = pageNumber - 1;
        } else {
            this.pageNumber = 0;
        }
        this.pageSize = pageSize;
    }

    public Page(int pageNumber, int pageSize, int totalPages, long totalElements) {

        this(pageNumber, pageSize);
        this.totalPages = totalPages;
        this.totalElements = totalElements;
    }

    public Page(HttpServletRequest request, HttpServletResponse response) {

        String numberStr = request.getParameter("page");
        String sizeStr = request.getParameter("size");
        int page = StringUtils.isBlank(numberStr) ? 0 : Integer.parseInt(numberStr);
        if (page >= 1) {
            this.pageNumber = page - 1;
        } else {
            this.pageNumber = 0;
        }
        this.pageSize = StringUtils.isBlank(sizeStr) ? 20 : Integer.parseInt(sizeStr);

    }

    public int getPageNumber() {
        return pageNumber;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public long getTotalElements() {
        return totalElements;
    }

    public List<T> getContent() {
        return content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    /**
     * 转换Page对象
     * @param call 转换接口
     * @param <D> 目标类型
     * @return 目标对象
     */
    public <D> D convertPage(ConvertCall<T, D> call) {
        return call.execute(this);
    }

}
